import Vue from 'vue'
import Router from 'vue-router'


// 路由懒加载
const Login = () => import(/* webpackChunkName: "Login_Home_Welcome" */ '@/components/login')
const Item = () => import(/* webpackChunkName: "Login_Home_Welcome" */ '@/components/item')
const About = () => import(/* webpackChunkName: "Login_Home_Welcome" */ '@/views/About')
const Pop = () => import(/* webpackChunkName: "Login_Home_Welcome" */ '@/components/pop')
const Zcool = () => import(/* webpackChunkName: "Login_Home_Welcome" */ '@/components/zcool')
const Page = () => import(/* webpackChunkName: "Login_Home_Welcome" */ '@/components/page')
const Home = () => import(/* webpackChunkName: "Login_Home_Welcome" */ '@/views/Home')

Vue.use(Router)

const routes = [
  { path: '/login', component: Login },
  { path: '/',  
    component: Home, 
    children: [
      { path: '/item', component: Item },
      { path: '/zcool', component: Zcool },
      { path: '/About', component: About },
    ] },
    { path: '/pop', component: Pop },
    { path: '/page/:id', component: Page ,meta: { loginRequest:true } },
    { path: '*', component: ()=> import('@/views/error/404')},
    
]

const router = new Router({
  // mode:'history',  //去除#
  routes
})

// 挂载路由导航守卫,to表示将要访问的路径，from表示从哪里来，next是下一个要做的操作 next('/login')强制跳转login
router.beforeEach((to, from, next) => {

  // 访问登录页，放行
  // 获取token
  const tokenStr = window.sessionStorage.getItem('token')
  // // 没有token, 强制跳转到登录页
  if(to.meta.loginRequest){
    if(!tokenStr){
      return next({
        path:'/login',
        query:{
          redirect:to.fullPath
        }
      })
    }return next()
  }else{
  if (to.path === '/login') return next()
  if (!tokenStr) return next('/login')
  next()
  }
})


export default  router

